import { useState } from 'react';
import { ContractPromise } from '@polkadot/api-contract';
import usePolkadot from './usePolkadot';
import type { Abi } from '@polkadot/api-contract';

type TransactionResult = {
    success: boolean;
    error?: string;
    gasRequired?: any;
    output?: any;
};

const useTransaction = () => {
    const { polkadotApi, address, signer } = usePolkadot();
    const [pending, setPending] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const gasLimit = 3000n * 1000000n;
    const storageDepositLimit = 1;

    const handleError = (error: string) => {
        setError(error);
        setPending(false);
    };

    // 执行查询方法
    const executeQuery = async (
        methodName: string, // 合约查询方法名
        params: unknown[], // 合约查询方法参数
        contractAddress: string, // 合约地址
        metadata: Abi // 合约的 ABI/元数据
    ): Promise<TransactionResult> => {
        if (!polkadotApi || !address) {
            handleError('Polkadot API is not ready.');
            return { success: false, error: 'Polkadot API is not ready.' };
        }

        setPending(true);
        setError(null);

        try {
            const contract = new ContractPromise(polkadotApi, metadata, contractAddress);
            const { result, gasRequired, output } = await contract.query[methodName](
                address, // 当前账户地址
                { gasLimit, storageDepositLimit }, // gas 限制
                ...params // 参数
            );

            if (result.isOk) {
                return { success: true, gasRequired: gasRequired.toHuman(), output: output?.toHuman() };
            } else {
                const errorMsg = result.asErr.toString();
                handleError(errorMsg);
                return { success: false, error: errorMsg };
            }
        } catch (err) {
            console.error('Error interacting with contract:', err);
            handleError('Error interacting with contract');
            return { success: false, error: 'Error interacting with contract' };
        }
    };

    // 执行交易方法
    const executeTx = async (
        methodName: string, // 合约操作方法名
        params: unknown[], // 合约操作方法参数
        contractAddress: string, // 合约地址
        metadata: Abi, // 合约的 ABI/元数据
    ): Promise<TransactionResult> => {
        if (!polkadotApi || !address) {
            handleError('Polkadot API is not ready.');
            return { success: false, error: 'Polkadot API is not ready.' };
        }

        setPending(true);
        setError(null);

        try {
            const contract = new ContractPromise(polkadotApi, metadata, contractAddress);
            const unsub = await contract.tx[methodName](
                { gasLimit },
                ...params // 参数
            ).signAndSend(address, { signer }, (status) => {
                console.log('Transaction status:', status);
                if (status.isFinalized || status.isInBlock) {
                    unsub();
                    setPending(false);
                }
            });

            return { success: true };
        } catch (err) {
            console.error('Error interacting with contract:', err);
            handleError('Error interacting with contract');
            return { success: false, error: 'Error interacting with contract' };
        }
    };

    return { pending, error, executeQuery, executeTx };
};

export default useTransaction;
